//计算笛卡尔积：data = [['a', 'b', 'c'], [1, 2, 3, 4], ['A', 'B'], ['#', '@', '+'], ['Mary', 'Terry', 'KYO']]
export function multiCartesian(data) {
  var ft = function (a, b) {
    if (!(a instanceof Array)) a = [a];
    var ret = Array.call(null, a);
    ret.push(b);
    return ret;
  };
  //两个的笛卡尔积
  var Cartesian = function (a, b) {
    var ret = [];
    for (var i = 0; i < a.length; i++) {
      for (var j = 0; j < b.length; j++) {
        ret.push(ft(a[i], b[j]));
      }
    }
    return ret;
  };
  //多个一起做笛卡尔积
  var result;
  var len = data.length;
  if (len == 0) result = [];
  else if (len == 1) result = data[0];
  else {
    var r = data[0];
    for (var i = 1; i < len; i++) {
      r = Cartesian(r, data[i]);
    }
    result = r;
  }
  return result;
}

//按指定关键字找元素，返回第一个匹配成功的下标
export function findIndexByKeyValue(arraytosearch, key, valuetosearch) {
  for (var i = 0; i < arraytosearch.length; i++) {
    if (arraytosearch[i][key] == valuetosearch) {
      return i;
    }
  }
  return -1;
}

//=========以前的=======================================================================
export function dateTime2Str(date, flag) {
  var year = date.getFullYear();
  var month = (date.getMonth() + 1).toString();
  var day = (date.getDate()).toString();
  var hour = date.getHours().toString();
  var minute = date.getMinutes().toString();
  var sec = date.getSeconds().toString();
  if (month.length == 1) {
    month = '0' + month;
  }
  if (day.length == 1) {
    day = '0' + day;
  }
  if (hour.length == 1) hour = '0' + hour;
  if (minute.length == 1) minute = '0' + minute;
  if (sec.length == 1) sec = '0' + sec;
  var dateTime = '';
  if (flag == 1) dateTime = year + '-' + month + '-' + day;
  else if (flag == 2) dateTime = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + sec;
  else if (flag == 3) dateTime = year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
  return dateTime;
}

export function sortByKey(array, key, type, asce) { //对象数组排序：关键字为可比大小的简单类型
  return array.sort(function (a, b) {
    var x = a[key];
    var y = b[key];

    var res = 0;
    if (type === 'int') {
      x = parseInt(x);
      if (!isRealNum(x)) x = -99;
      y = parseInt(y);
      if (!isRealNum(y)) y = -99;
      res = (x < y) ? -1 : ((x > y) ? 1 : 0);
      // console.log(x,y);    
    } else {
      // console.log(x,y);      
      if (x != null && y == null) res = 1;
      else if (x == null && y != null) res = -1;
      else if (x != null && y != null) {
        res = ((x < y) ? -1 : ((x > y) ? 1 : 0));
      }
    }

    if (asce) return res;
    else return -res;
  });
}

export function isRealNum(val) {
  if (val === '' || val == null) return false;
  if (!isNaN(val)) return true;
  return false;
}

export function isMobile(val) {
  return /^1\d{10}$/.test(val);
}

import request from '@/utils/request';
export function getAPIServerTime() //取API服务当前日期时间
{
  return request({
    url: '/Common/GetAPIServerTime',
    method: 'get',
  });
}
